#-*- coding: utf-8 -*-
from saltstack.models import salt_node_list

def node_list(start,end,key_status=None):
    context = {}
    try:
        count = 0
        nodelist = {}
        if key_status:
            count = salt_node_list.objects.filter(key_status=key_status).count()
            nodelist = salt_node_list.objects.filter(key_status=key_status).order_by("status")[start:end]
        else:
            count = salt_node_list.objects.all().count()
            nodelist = salt_node_list.objects.order_by("status")[start:end]
        list_return = []
        for i in nodelist:
            if key_status:
                list_return.append({'id':i.id,'minions':i.minions,'status':i.status})
            else:
                list_return.append({'id':i.id,'minions':i.minions,'status':i.status,'key_status':i.key_status})
        context['salt_key'] = list_return
        context['count'] = count
    except Exception,ex:
        print Exception,ex
    return context

def get_all_nodes():
    context = {}
    try:
        nodelist = salt_node_list.objects.filter(key_status=1).values('id','minions')
        context['salt_key'] = nodelist
    except Exception,ex:
        print Exception,ex
    return context

def search_nodes(minions):
    list_return = []
    try:
        nodelist = salt_node_list.objects.filter(minions__icontains=minions).values('minions')
        list_return = []
        for i in nodelist:
            list_return.append(i['minions'])
    except Exception,ex:
        print Exception,ex
    return list_return

def node_exists_check(minions):
    check = True
    try:
        count = salt_node_list.objects.filter(minions=minions).count()
        if count == 0:
            check = False
    except Exception,ex:
        check = False
        print Exception,ex
    return check

def update_salt_node(minions, status, cursor):
    nodeListSql = 'update salt_node_list set status = ' + status + ' where minions="' + minions + '"'
    cursor.execute(nodeListSql)

def update_salt_key_status(minions,key_status):
    saltNode = salt_node_list.objects.get(minions=minions)
    saltNode.key_status = key_status
    saltNode.save()

def delete_salt_node(minions, cursor):
    node_del = 'delete from salt_node_list where minions="' + minions + '"'
    cursor.execute(node_del)